import passport from 'koa-passport';
import { Strategy as LocalStrategy } from "passport-local";
import { Strategy as BearerStrategy } from "passport-http-bearer";
import { getUserByUsername, getToken } from "../models";
import { getHash } from "../utils";

passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser(async(username, done) => {
	done(null, await getUserByUsername(username));
});

passport.use('local', new LocalStrategy({
	usernameField:'username',
	passwordField:'password'
}, async(username, password, done) => {
	try{
		console.log(username);
		const user = await getUserByUsername(username);
		console.log(user);
		if(!user){
			return done(null, false);
		}
		if(getHash(password) === user.password){
			return done(null, user);
		} else {
			return done(null, false);
		}
	} catch (error) {
		done(error);
	}
}));

passport.use('bearer', new BearerStrategy(async(token, done) => {
	try{
		const accessToken = await getToken(token);
		if(!accessToken || typeof(accessToken) == 'undefined'){
			return done(null, false);
		}

		const curtime = new Date(); 
		if(curtime.getTime() - parseInt(accessToken.ctime) > 7200000){
			return done(null, false);
		}
		return done(null, accessToken.userId);
	} catch (error) {
		done(error);
	}
}))

export function isLocalAuthenticated(){
	return passport.authenticate('local', {session:false});
}

export function isBearerAuthenticated() {
	return passport.authenticate('bearer', {session:false});
}

export default passport;